<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" :size="size">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="门店名称" prop="shopName">
                            <el-select v-model="condition.search.shopName" filterable placeholder="请选择">
                                <el-option
                                    v-for="item in allShops"
                                    :key="item.id"
                                    :label="item.shopName"
                                    :value="item.shopName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="门店ID" prop="shopId">
                            <el-input v-model="condition.search.shopId"
                                      placeholder="门店ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="门店UUID" prop="shopUuid">
                            <el-input v-model="condition.search.shopUuid"
                                      placeholder="门店UUID"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="是否每日更新" prop="status">
                            <el-select v-model="condition.search.status" placeholder="是否每日更新">
                                <el-option label="是" :value="true"></el-option>
                                <el-option label="否" :value="false"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="是否同步CPC" prop="syncCpcStatus">
                            <el-select v-model="condition.search.syncCpcStatus" placeholder="是否同步CPC">
                                <el-option label="是" :value="true"></el-option>
                                <el-option label="否" :value="false"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="是否收藏" prop="favoriteFlag">
                            <el-select v-model="condition.search.favoriteFlag" placeholder="是否收藏">
                                <el-option label="是" :value="true"></el-option>
                                <el-option label="否" :value="false"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="showAddDialog">系统新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="warning" @click="manualAddDialogVisible = true">手工新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="danger" @click="timeOrder">
                                {{
                                    orderRank ? '名称排序' : '时间排序'
                                }}
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <div class="el-tips">
                            温馨提示：不合作的商户尽早删除；
                        </div>
                        <div class="el-tips">
                            棕色代表：推广通Cookie已经失效，需要重新填写，红色代表：评价Cookie已经失效，需要重新填写，一般失效周期在一个礼拜左右，如果发现某个门店经常失效，那肯定是哪里设置有问题，请联系管理员；
                        </div>
                        <div class="el-tips">
                            <el-link href="https://docs.qq.com/doc/DSmh5RlJpZEpuTENm" type="success" target="_blank">
                                点击查看教程
                            </el-link>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            :size="size"
            id="mainTable"
            :data="tableData"
            row-key="id"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="60" fixed="left">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="shopName"
                fixed="left"
                width="100px"
                label="门店名称">
                <template v-slot="scope">
                    <el-link @click="clickShopName(scope.row)">
                        {{ scope.row.shopName }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column
                prop="shopId"
                width="100px"
                label="门店ID">
            </el-table-column>
            <el-table-column
                prop="shopUuid"
                width="100px"
                label="门店UUID">
            </el-table-column>
            <el-table-column
                prop="poiId"
                width="100px"
                label="位置ID">
            </el-table-column>
            <el-table-column
                prop="syncDate"
                label="同步日期">
            </el-table-column>
            <el-table-column
                prop="categoryName"
                label="分类">
            </el-table-column>
            <el-table-column
                prop="cityName"
                label="城市">
            </el-table-column>
            <el-table-column
                prop="avgPrice"
                width="60px"
                label="人均">
            </el-table-column>
            <el-table-column
                prop="rankNameEx"
                width="100px"
                label="榜单">
            </el-table-column>
            <el-table-column
                prop="mainScore"
                width="60px"
                label="大分">
            </el-table-column>
            <el-table-column
                prop="tasteScore"
                width="60px"
                label="口味分">
            </el-table-column>
            <el-table-column
                prop="envScore"
                width="60px"
                label="环境分">
            </el-table-column>
            <el-table-column
                prop="serviceScore"
                width="60px"
                label="服务分">
            </el-table-column>
            <el-table-column
                prop="foodScore"
                width="60px"
                label="食材分">
            </el-table-column>
            <el-table-column
                prop="picCount"
                label="图片数量">
            </el-table-column>
            <el-table-column
                prop="reserveCount"
                label="预定数量">
            </el-table-column>
            <el-table-column
                prop="reviewCount"
                label="评论数量">
            </el-table-column>
            <el-table-column
                prop="favorNum"
                label="收藏量">
            </el-table-column>
            <el-table-column
                prop="favorSyncDate"
                label="收藏日期">
            </el-table-column>
            <el-table-column
                prop="status"
                :formatter="formatStatus"
                label="是否更新">
            </el-table-column>
            <el-table-column
                prop="syncCpcStatus"
                :formatter="formatStatus"
                label="同步CPC">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                prop="createBy"
                label="谁创建的">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                prop="updateBy"
                label="谁更新的">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="200">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onDetail(scope.row)" type="text" size="small">详情</el-button>
                        <el-button @click="onRefresh(scope.row)" type="text" size="small">刷新</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="up(scope.$index)" type="text" size="small">上移</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[100, 200]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="150px" :size="size">
                <el-form-item label="门店UUID">
                    <el-input v-model="addOrUpdateForm.shopUuid" :disabled="disabled"
                              placeholder="门店UUID"></el-input>
                    <div class="form-tips">获取方式，大众点评APP，进入门店详情，右上角分享，复制分享链接，里面就有uuid</div>
                </el-form-item>
                <el-form-item label="是否更新">
                    <el-switch v-model="addOrUpdateForm.status"></el-switch>
                </el-form-item>
                <el-form-item label="同步CPC">
                    <el-switch v-model="addOrUpdateForm.syncCpcStatus"></el-switch>
                </el-form-item>
                <el-form-item label="是否收藏">
                    <el-switch v-model="addOrUpdateForm.favoriteFlag"></el-switch>
                </el-form-item>
                <el-form-item label="是否开通过推广通">
                    <el-switch v-model="addOrUpdateForm.cpcFlag"></el-switch>
                </el-form-item>
                <el-form-item label="评价链接">
                    <el-input v-model="addOrUpdateForm.feedbackUrls" placeholder="评价链接" :autosize="{ minRows: 2}"
                              type="textarea"></el-input>
                    <div class="form-tips">用于获取收藏量，多个用逗号英文逗号分隔</div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false" :size="size">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="手工新增" width="30%" :visible.sync="manualAddDialogVisible">
            <el-form :model="manualForm" label-width="150px" :size="size">
                <el-form-item label="门店UUID">
                    <el-input v-model="manualForm.shopUuid" :disabled="disabled"
                              placeholder="门店UUID"></el-input>
                    <div class="form-tips">获取方式，大众点评APP，进入门店详情，右上角分享，复制分享链接，里面就有uuid</div>
                </el-form-item>
                <el-form-item label="门店ID">
                    <el-input v-model="manualForm.shopId" :disabled="disabled"
                              placeholder="门店ID"></el-input>
                    <div class="form-tips">获取方式，开店宝APP，我的，门店信息，点评ID</div>
                </el-form-item>
                <el-form-item label="位置ID">
                    <el-input v-model="manualForm.poiId" :disabled="disabled"
                              placeholder="位置ID"></el-input>
                    <div class="form-tips">新店跟门店ID一样，老店需要去网页开店宝后台获取，具体可以咨询管理员</div>
                </el-form-item>
                <el-form-item label="门店名称">
                    <el-input v-model="manualForm.shopName" :disabled="disabled"
                              placeholder="门店名称"></el-input>
                    <div class="form-tips">包含分店名称</div>
                </el-form-item>
                <el-form-item label="是否更新">
                    <el-switch v-model="manualForm.status"></el-switch>
                </el-form-item>
                <el-form-item label="同步CPC">
                    <el-switch v-model="manualForm.syncCpcStatus"></el-switch>
                </el-form-item>
                <el-form-item label="是否收藏">
                    <el-switch v-model="manualForm.favoriteFlag"></el-switch>
                </el-form-item>
                <el-form-item label="是否开通过推广通">
                    <el-switch v-model="manualForm.cpcFlag"></el-switch>
                </el-form-item>
                <el-form-item label="评价链接">
                    <el-input v-model="manualForm.feedbackUrls" placeholder="评价链接" :autosize="{ minRows: 2}"
                              type="textarea"></el-input>
                    <div class="form-tips">用于获取收藏量，多个用逗号英文逗号分隔</div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="manualAddDialogVisible = false" :size="size">取 消</el-button>
                <el-button @click="manualAddConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addDpShop,
    addDpShopManual,
    changeDpShopOrder,
    deleteDpShop,
    getAllShops,
    getDpShopByPageExt,
    refreshDpShop,
    updateDpShop,
    upDpShopOrder
} from '@/api/api'
import Sortable from 'sortablejs'

export default {
    name: "dp-shop",
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 100,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            // 禁用
            disabled: false,

            // 所有门店
            allShops: [],

            // 时间排序
            orderRank: false,

            manualAddDialogVisible: false,
            manualForm: {
                'status': false,
                'syncCpcStatus': false,
                'favoriteFlag': false,
                'cpcFlag': true,
            },
        }
    },
    watch: {
        $route: function (newVal, oldVal) {
            let page = newVal.query.page;
            if (page) {
                this.condition.page = Number(page);
            }
            let rows = newVal.query.rows;
            if (rows) {
                this.condition.rows = Number(rows);
            }
            this.getData();
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        size: {
            type: String,
            default: 'small'
        },
    },
    methods: {
        clickShopNameEx(row) {
            let url = "https://m.dianping.com/shopshare/" + row.shopUuid + "?msource=Appshare2021&utm_source=shop_share"
            window.open('javascript:window.name;', '<script>location.replace("' + url + '")<\/script>');
        },
        clickShopName(row) {
            this.onDetail(row);
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            if (row.reserveCookie) {
                if (row.reserveCookieAvailable != null) {
                    if (!row.reserveCookieAvailable) {
                        return 'reserve-cookie-unavailable'
                    }
                }
            }
            if (row.promotionCookie) {
                if (row.promotionCookieAvailable != null) {
                    if (!row.promotionCookieAvailable) {
                        return 'promotion-cookie-unavailable'
                    }
                }
            }
            return '';
        },
        handleSizeChange(val) {
            let queryParams = {page: this.condition.page, rows: this.condition.rows};
            this.$router.push({query: queryParams});
        },
        handleCurrentChange(val) {
            let queryParams = {page: this.condition.page, rows: this.condition.rows};
            this.$router.push({query: queryParams});
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatStatus: function (row, column, cellValue) {
            if (cellValue == undefined) {
                return "";
            }
            if (cellValue == '0') {
                return "否";
            } else if (cellValue == '1') {
                return "是";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            this.$set(this.addOrUpdateForm, "status", false)
            this.$set(this.addOrUpdateForm, "syncCpcStatus", false)
            this.$set(this.addOrUpdateForm, "favoriteFlag", false)
            this.$set(this.addOrUpdateForm, "cpcFlag", true)
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
            this.disabled = true;
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        timeOrder: function () {
            this.orderRank = !this.orderRank;
            this.getData();
        },
        add: function () {
            addDpShop(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateDpShop(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        manualAddConfirm: function () {
            addDpShopManual(this.manualForm).then(data => {
                if (data.respCode == 1000) {
                    this.manualAddDialogVisible = false;
                    this.getData();
                }
            });
        },
        onDetail: function (row) {
            this.$router.push({path: '/dp/shop/detail', query: {shopId: row.shopId}});
        },
        onRefresh: function (row) {
            this.$confirm('请确认是否刷新, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                refreshDpShop({id: row.id}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '刷新成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteDpShop({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            let params = {};
            params.orderRank = this.orderRank;
            getDpShopByPageExt(params, this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
            getAllShops().then(data => {
                this.allShops = data.body;
            })
        },
        // 上移
        up(index) {
            console.log(index);
            if (index === 0) {
                this.$message({
                    type: 'info',
                    message: '当前行不能往上移动！！'
                });
                return;
            }
            let data = {};
            data.id = this.tableData[index].id;
            data.swapId = this.tableData[index - 1].id;
            upDpShopOrder(data).then(res => {
                this.getData();
            })
        },
        // 行拖拽
        rowDrop() {
            // 此时找到的元素是要拖拽元素的父容器
            const tbody = document.querySelector('.el-table__body-wrapper tbody');
            const _this = this;
            Sortable.create(tbody, {
                //  指定父元素下可被拖拽的子元素
                draggable: ".el-table__row",
                onEnd({newIndex, oldIndex}) {
                    if (true) {
                        _this.$message({
                            type: 'info',
                            message: '脱动排序功能暂未实现！！'
                        });
                    }
                    let old = _this.tableData[oldIndex];
                    const currRow = _this.tableData.splice(oldIndex, 1)[0];
                    _this.tableData.splice(newIndex, 0, currRow);
                    let desc = _this.tableData[newIndex + 1];
                    console.log(oldIndex)
                    console.log(newIndex);
                    console.log(old);
                    console.log(desc);
                    // 功能暂未实现
                    let data = {};
                    changeDpShopOrder(data).then(res => {
                        _this.getData();
                    })
                }
            });
        },
    },
    created() {
        let page = this.$route.query.page;
        if (page) {
            this.condition.page = Number(page);
        }
        let rows = this.$route.query.rows;
        if (rows) {
            this.condition.rows = Number(rows);
        }
        this.getData();
    },
    mounted() {
        this.rowDrop();
    }
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
